package databaseTransaction;

import java.io.FileWriter;
import java.io.IOException;
import java.util.Properties;

import util.ClassInformation;
import util.Configuration;
import util.ConnectionConfig;
import util.FolderPath;
import util.Tag;
import util.TypeOfDatabaseSystem;

import codeGeneration.Generator;

public class DataSourceGenerator extends Generator {
	private FileWriter fileWriter;

	public void getDataSourceBean(int typeOfDBS, Configuration config) {
		String className = "";

		switch (typeOfDBS) {
		case TypeOfDatabaseSystem.MYSQL:
			className = "com.mysql.jdbc.jdbc2.optional.MysqlDataSource";
			break;
		case TypeOfDatabaseSystem.MSSQLSERVER:
			className = "com.microsoft.sqlserver.jdbc.SQLServerDataSource";
			break;
		}

		ClassInformation classInformation = config
				.checkWithIDOfBean("dataSource");
		classInformation.setClassName(className);

		Properties prop = new Properties();
		prop.put("user", "${jdbc.user}");
		prop.put("password", "${jdbc.password}");
		prop.put("serverName", "${jdbc.serverName}");
		prop.put("port", "${jdbc.port}");
		prop.put("databaseName", "${jdbc.databaseName}");
		classInformation.setChildTags(Tag.makeTagForBeanProperty(prop));
	}

	public void generateProperties(FolderPath folderPath,
			ConnectionConfig connConfig) throws IOException {
		String user = connConfig.getUser();
		String password = connConfig.getPassword();
		String serverName = connConfig.getServerName();
		String port = connConfig.getPort();
		String databaseName = connConfig.getDatabaseName();

		fileWriter = getFileWriter(folderPath.getSrcPath() + "/jdbc.properties");
		fileWriter.append("jdbc.serverName=" + serverName + "\n");
		fileWriter.append("jdbc.user=" + user + "\n");
		fileWriter.append("jdbc.password=" + password + "\n");
		fileWriter.append("jdbc.port=" + port + "\n");
		fileWriter.append("jdbc.databaseName=" + databaseName);

		closeFileWriter(fileWriter);
	}
}